package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 交友模块业务
 */
@Service
public class RecommendUserService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private UserLocationApi userLocationApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 今日佳人
     *
     * @return
     */
    public RecommendUserVo todayBest() {
        //1. 获取登录用户id
        Long loginUserId = UserHolder.getUserId();
        //2. 调用mongoApi查询推荐给登录用户的佳人
        RecommendUser todayBest = recommendUserApi.findTodayBest(loginUserId);
        //3. 非空判断, 默认给客服
        if (null == todayBest) {
            todayBest = new RecommendUser();
            todayBest.setUserId(loginUserId % 99 + 1); // 1-99id的客服
            todayBest.setScore(RandomUtils.nextDouble(70, 88));
        }
        //4. 查询佳人的信息
        UserInfo userInfo = userInfoApi.findById(todayBest.getUserId());
        //5. 转成vo
        RecommendUserVo vo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(StringUtils.split(userInfo.getTags(), ","));
        // 缘分值
        vo.setFateValue(todayBest.getScore().longValue());
        //6. 返回
        return vo;
    }

    /**
     * 首页推荐-分页查询
     *
     * @param queryParam
     * @return
     */
    public PageResult<RecommendUserVo> recommendList(RecommendUserQueryParam queryParam) {
        //1. 获取登录用户的id
        Long loginUserId = UserHolder.getUserId();
        //2. 远程调用recommendUserApi,通过登录用户id分页查询好友推荐表(mongodb: recommend_user where toUserId=登录用户id)
        // 得到pageResult
        PageResult pageResult = recommendUserApi.findPageBy2UserId(loginUserId, queryParam.getPage(), queryParam.getPagesize());
        //2.1 获取分页的结果集
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();
        //2.2 如果结果集为空，
        if (CollectionUtils.isEmpty(recommendUserList)) {
            //没有推荐则给客服（默认推荐好友）
            recommendUserList = getDefaultRecommendUserList();
            pageResult.setCounts(10l);
            pageResult.setPages(1l);
        }
        //3. 遍历分页结果集
        List<RecommendUserVo> voList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            //3.1 取出佳人id(recommendUser.getUserId())
            Long userId = recommendUser.getUserId();
            //3.2 查询佳人们的信息(tb_user_info)
            UserInfo userInfo = userInfoApi.findById(userId);
            //3.3 转成vo
            RecommendUserVo vo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo, vo);
            vo.setTags(StringUtils.split(userInfo.getTags(), ","));
            // 缘分值
            vo.setFateValue(recommendUser.getScore().longValue());
            //3.4 把vo添加到voList集合
            voList.add(vo);
        }
        //4. 把voList设置到pageResult
        pageResult.setItems(voList);
        //6. 返回 pageResult
        return pageResult;
    }

    /**
     * 给默认10个客户为推荐好友
     *
     * @return
     */
    private List<RecommendUser> getDefaultRecommendUserList() {
        List<RecommendUser> list = new ArrayList<>();
        for (long i = 1; i <= 10; i++) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i);
            recommendUser.setScore(RandomUtils.nextDouble(70, 88));
            list.add(recommendUser);
        }
        return list;
    }

    /**
     * 查看佳人信息
     *
     * @param userId
     * @return
     */
    public RecommendUserVo getPersonalInfo(Long userId) {
        //1. 通过佳人id查询用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2. 查询佳人与登录用户的缘分值
        Double score = recommendUserApi.queryForScore(UserHolder.getUserId(), userId);
        //3. 如果没有查到缘分值，给随机
        if (null == score) {
            score = RandomUtils.nextDouble(70, 88);
        }
        //4. 转成vo返回
        RecommendUserVo vo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(StringUtils.split(userInfo.getTags(), ","));
        // 缘分值
        vo.setFateValue(score.longValue());
        return vo;
    }

    /**
     * 查询佳人设置 的陌生人问题
     *
     * @param userId
     * @return
     */
    public String getStrangerQuestion(Long userId) {
        //1. 调用api查询佳人设置的陌生人问题
        Question question = questionApi.findByUserId(userId);
        //2. 如果没查到，没设置给默认值
        if (null == question) {
            return "你喜欢我吗,要约吗?";
        }
        return question.getTxt();
    }

    /**
     * 回复佳人设置 的陌生人问题
     *
     * @param paramMap (userId佳人id, reply回复内容)
     */
    public void replyStrangerQuestions(Map<String, Object> paramMap) {
        //1. 查询登录用户信息
        UserInfo loginUserInfo = userInfoApi.findById(UserHolder.getUserId());
        //2. 查询佳人的陌生人问题
        Long userId = ((Integer) paramMap.get("userId")).longValue();
        Question question = questionApi.findByUserId(userId);
        //3. 构建消息内容
        Map<String, Object> map = new HashMap<>();
        map.put("userId", UserHolder.getUserId()); // 发送者id 登录用户id
        map.put("nickname", loginUserInfo.getNickname()); // 发送者昵称 登录用户的昵称
        map.put("strangerQuestion", null == question ? "你喜欢我吗,要约吗?" : question.getTxt());
        map.put("reply", ((String) paramMap.get("reply")));
        String msg = JSON.toJSONString(map);
        //4. 发送消息
        huanXinTemplate.sendMsg(userId.toString(), msg);
    }

    //(String) paramMap.get("reply")  区别  paramMap.get("reply").toString()
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("a", null);

        //System.out.println(map.get("a").toString());
        System.out.println((String) map.get("a"));
    }

    /**
     * 搜附近
     *
     * @param gender
     * @param distance 圆的半径
     * @return
     */
    public List<NearUserVo> searchNearBy(String gender, Long distance) {
        //1. 通过登录用户的坐标搜附近, 得到结果集,
        List<UserLocationVo> locationList = userLocationApi.searchNearBy(UserHolder.getUserId(), distance);
        List<NearUserVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(locationList)) {
            //2. 过滤性别
            //2.1 查询用户信息
            List<Long> userIds = locationList.stream().map(UserLocationVo::getUserId).collect(Collectors.toList());
            List<UserInfo> userInfoList = userInfoApi.findByBatchId(userIds);
            // 过滤性别 filter: 相同的留下，不同的过滤掉
            //3. 转成vo, 把userInfoList集合中的每个元素先进行性别过滤（性别相同的留下，不相同的过滤掉）
            //          再转成vo， 收集到list里
            voList = userInfoList.stream().filter(u -> u.getGender().equals(gender))
                    .map(u -> new NearUserVo(u.getId(), u.getAvatar(), u.getNickname()))
                    .collect(Collectors.toList());

        }
        //4. 返回
        return voList;
    }

    /**
     * 桃花传音（喜欢）
     *
     * @param userId
     */
    public void love(Long userId) {
        Long loginId = UserHolder.getUserId();
        UserLike userLike = new UserLike();
        userLike.setUserId(loginId);
        userLike.setLikeUserId(userId);
        Date date = new Date();
        userLike.setCreated(date.getTime());
        recommendUserApi.like(loginId, userLike);

    }

    /**
     * 桃花传音（不喜欢）
     *
     * @param userId
     */
    public void unlove(Long userId) {
        Long loginId = UserHolder.getUserId();
        recommendUserApi.unlove(userId,loginId);
    }
}
